package com.example.springbootjwt.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.jwt.JWT;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

/**
 * JWT 操作-带过期时间验证：使用 hutool 框架提供 api
 * hutool 文档说明：https://hutool.cn/docs/#/jwt/JWT%E9%AA%8C%E8%AF%81-JWTValidator
 */
@RestController
@RequestMapping("/jwtdate")
public class JwtDateController {
    // JWT 私有秘钥
    private final String secretKey = "java666";

    @RequestMapping("/create")
    public String create(Long userid, String username) {
        if (userid == null || !StringUtils.hasLength(username)) {
            return "fail";
        }
        String token = JWT.create()
                .setPayload("userid", userid)
                .setPayload("username", username)
//                .setExpiresAt(DateUtil.nextWeek()) // 1个月后过期
                .setExpiresAt(DateUtil.offsetSecond(new Date(), 30)) // 30s 后过期
                .setKey(secretKey.getBytes())
                .sign();
        return token;
    }

    @RequestMapping("/get")
    public String decode(String token) {
        if (!StringUtils.hasLength(token)) {
            return "fail";
        }
        // 得到 JWT
        JWT jwt = JWT.of(token)
                .setKey(secretKey.getBytes());
        // JWT 签名验证
        boolean verify = jwt.verify();
        if (verify) { // 签名验证成功
            // JWT 过期时间验证
            boolean validata = jwt.validate(0);
            System.out.println("validata:" + validata);
            if (validata) {
                Long userid = Long.parseLong(jwt.getPayload("userid").toString());
                String username = jwt.getPayload("username").toString();
                String userinfo = "userid=" + userid +
                        " | username=" + username;
                System.out.println(userinfo);
                return userinfo;
            } else {
                System.out.println("token 已过期");
                return "token 已过期";
            }

        }
        return "last fail";
    }
}
